package com.example.demo.controller;

import com.example.demo.dao.AppDao;
import com.example.demo.dao.CollectDao;
import com.example.demo.entity.App;
import com.example.demo.entity.Collect;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * (Collection)表控制层
 *
 * @author makejava
 * @since 2022-06-11 22:00:20
 */
@RestController
@RequestMapping("collection")
public class CollectionController {
    /**
     * 服务对象
     */
    @Autowired
    private CollectDao collectDao;
    @Autowired
    private AppDao appDao;

    /**
     * 分页查询
     *
     * @param tabcollect 筛选条件
     * @return 查询结果
     */
    @RequestMapping("/list")
    public Object queryByPage(Collect tabcollect, HttpSession session) {
        String userId = session.getAttribute("USER_ID").toString();
        tabcollect.setUserId(Integer.valueOf(userId));
        return collectDao.queryAllByLimit(tabcollect);
    }


    /**
     * 推荐-猜你喜欢
     *
     * @param
     * @return 查询结果
     */
    @RequestMapping("/recommend")
    public Object recommend(HttpSession session) {
        //1.判断用户是否登录 未登录 返回空
        if (session.getAttribute("USER_ID") == null) {
            return new ArrayList<>();
        }
        //2.获取当前登陆人的用户id
        String userId = session.getAttribute("USER_ID").toString();

        // 3.获取用户收藏信息
        List<Integer> collectTypeIds = collectDao.userCollectType(userId);
        //如果用户收藏的电影是空 走系统推荐
        if (CollectionUtils.isEmpty(collectTypeIds)) {
            return   collectDao.appRandByCollectType1();
        }
        //根据用户收藏的电影推荐
        return collectDao.appRandByCollectType(userId);
    }

    /**
     * 新增数据
     *
     * @param id 应用id
     * @return 新增结果
     */
    @RequestMapping("/add")
    public Object add(@RequestParam("id") String id, HttpSession session) {

        String userId = (String) session.getAttribute("USER_ID").toString();
        // 用户是否收藏
        Collect collect = collectDao.queryByAppIdAndUserId(Integer.valueOf(id), userId);
        // 未收藏
        if (collect == null) {
            App app = appDao.queryById(Integer.valueOf(id));
            Collect c = new Collect();
            BeanUtils.copyProperties(app, c);
            c.setUserId(Integer.valueOf(userId));
            c.setAppId(app.getId());
            c.setId(null);
            collectDao.insert(c);
            return "ok";
        }
        // 取消收藏
        collectDao.deleteById(collect.getId());
        return "cancel";
    }

}
